from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import TemplateDoesNotExist
from django.views.generic.simple import direct_to_template #about_pages view
from django.shortcuts import render_to_response
#from forms import ReactionForm #for add_rea view, then reactionform should be defined in forms.py, can also be here
from ehmn2.models import *
from settings import MEDIA_ROOT
from string import split
from django import forms
from django.db.models import Q
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import pydot
colors=[]
for i in range(1,100):
   s3=str((i % 5)/4.0)
   s2=i/5
   if s2>4:
      s1=str(s2/5/2.0)
      s2=str((s2 %5)/4.0)
   else:
#      if i==4:
#         s3="0.000" #replace white with black
      s1="0.000"
      s2=str(s2/4.0)
   colors.append(s3+" "+s1+" "+s2)

def loginview(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # return HttpResponseRedirect("http://csb.inf.ed.ac.uk/ehmn2")
        else:
           e='wrong'
           return render_to_response('thanks.html', {'eid': e}) #do sth else 
    else:
       e='wrong'
       return render_to_response('thanks.html', {'eid': e}) #do sth else 

def logout_view(request):
    logout(request)
    # Redirect to a success page.
 
class searchform(forms.Form):
    se_options=[('rea','reaction ID'),('com','compound ID or name'),('entrez','entrez gene ID or name'),
    ('hgen','HGNC or Ensembl ID'),('uniprot','Uniprot ID'),('ec','EC number'),('dig','genes related with disease'),
    ('dita','taget for disease'), ('drug','targeted by drug')]
    sefor_options=[('rea','reactions'),('com','compounds'),('gene','genes')]
    plist=Pathway.objects.all()
    p_options=[(0,'all')]
    for a in plist:
       p_options.append(((a.pathid),(a.name)))
    lolist=Location.objects.all()
    loptions=[(0,'all')]
    for a in lolist:
       loptions.append(((a.id),(a.des)))
    tlist=Tissue.objects.all()
    toptions=[(0,'all')]
    for a in tlist:
       toptions.append(((a.id),(a.name)))
    se=forms.ChoiceField(label="Search by", choices=se_options,required=False)
    sefor=forms.ChoiceField(label="for", choices=sefor_options,initial='rea')
    seterm=forms.CharField(label="matching", required=False)
    pa=forms.MultipleChoiceField(label="select pathways", choices=p_options, initial=0,required=False)
    lo=forms.MultipleChoiceField(label="subcellular location", choices=loptions,initial=0,required=False)
    t=forms.MultipleChoiceField(label="Tissue", choices=toptions,initial=0,required=False)
#    pa=forms.ChoiceField(label="select pathways", widget=forms.SelectMultiple, choices=p_options)

@login_required
def search(request):
    if request.method == 'GET':
        f = searchform(request.GET)
        if not f.is_valid():
           return render_to_response('search2.html', {'form': f}) #do sth else 
        else:
           if f.cleaned_data["sefor"]:
             if f.cleaned_data["sefor"]=='rea':
                if f.cleaned_data["seterm"]:
                  if f.cleaned_data["se"]=='rea':
                    s= f.cleaned_data["seterm"]
                    ids=split(s,",") 
                    objs = Reaction.objects.filter(reactionid__in=ids)
                  if f.cleaned_data["se"]=='com':
                    qset = (
                      Q(equation__icontains=f.cleaned_data["seterm"]) |
                      Q(eq_in_id__icontains=f.cleaned_data["seterm"]) 
                    )
                    objs = Reaction.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='entrez':
                    s= f.cleaned_data["seterm"]
                    ids=split(s,",") 
                    qset = (
                      Q(rea_gene__gene__name__in=ids) |
                      Q(rea_gene__gene__geneid__in=ids) 
                    )
                    objs = Reaction.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='hgen':
                    s= f.cleaned_data["seterm"]
                    ids=split(s,",") 
                    qset = (
                      Q(rea_gene__gene__hgnc__in=ids) |
                      Q(rea_gene__gene__ensembl__in=ids) 
                    )
                    objs = Reaction.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='uniprot':
                    qset = (
                      Q(rea_gene__gene__uniprot__icontains=f.cleaned_data["seterm"]) |
                      Q(rea_gene__gene__altprotein__icontains=f.cleaned_data["seterm"]) 
                    )
                    objs = Reaction.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='ec':
                    objs = Reaction.objects.filter(rea_ec__enzyme=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='dig':
                    objs = Reaction.objects.filter(rea_gene__gene__morbid__disorder__icontains=f.cleaned_data["seterm"]).distinct()
                    global dis_res
                    dis_res=[]
                    for res in objs.values('reactionid'):
                      dis_res.append(res['reactionid'])
                  if f.cleaned_data["se"]=='dita':
                    objs = Reaction.objects.filter(rea_gene__gene__dis_target__disease__icontains=f.cleaned_data["seterm"]).distinct()
                    global dit_res
                    dit_res=[]
                    for res in objs.values('reactionid'):
                      dit_res.append(res['reactionid'])
                  if f.cleaned_data["se"]=='drug':
                    objs = Reaction.objects.filter(rea_gene__gene__drug_target__drug__icontains=f.cleaned_data["seterm"]).distinct()
                else:
                  objs=Reaction.objects.all()
                if f.cleaned_data["pa"]:
                  if not f.cleaned_data["pa"][0][0]=='0':
                    objs=objs.filter(pathway__in=f.cleaned_data["pa"]).distinct()     
                if f.cleaned_data["lo"]:
                  if not f.cleaned_data["lo"][0][0]=='0':
                    objs=objs.filter(realoc__loc__in=f.cleaned_data["lo"]).distinct()     
                if f.cleaned_data["t"]:
                  if not f.cleaned_data["t"][0][0]=='0':
                    objs=objs.filter(rea_tissue__tissue__in=f.cleaned_data["t"]).distinct()     
#                return render_to_response('search1.html', {'form': f, 'reactions': objs, 'nre': nre})
                request.session['ehmnr']=objs
                return render_to_response('reaction_list2.html', {'reaction_list': objs})
             if f.cleaned_data["sefor"]=='com':
                if f.cleaned_data["seterm"]:
                  if f.cleaned_data["se"]=='rea':
                    objs = Compound.objects.filter(rea_comp__reaction__reactionid__icontains=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='com':
                    qset = (
                      Q(name__icontains=f.cleaned_data["seterm"]) |
                      Q(compoundid__icontains=f.cleaned_data["seterm"]) 
                    )
                    objs = Compound.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='entrez':
                    qset = (
                      Q(rea_comp__reaction__rea_gene__gene__name=f.cleaned_data["seterm"]) |
                      Q(rea_comp__reaction__rea_gene__gene__geneid=f.cleaned_data["seterm"]) 
                    )
                    objs = Compound.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='hgen':
                    qset = (
                      Q(rea_comp__reaction__rea_gene__gene__hgnc=f.cleaned_data["seterm"]) |
                      Q(rea_comp__reaction__rea_gene__gene__ensembl=f.cleaned_data["seterm"]) 
                    )
                    objs = Compound.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='uniprot':
                    qset = (
                      Q(rea_comp__reaction__rea_gene__gene__uniprot__icontains=f.cleaned_data["seterm"]) |
                      Q(rea_comp__reaction__rea_gene__gene__altprotein__icontains=f.cleaned_data["seterm"]) 
                    )
                    objs = Compound.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='ec':
                    objs = Compound.objects.filter(rea_comp__reaction__rea_ec__enzyme=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='dig':
                    objs = Compound.objects.filter(rea_comp__reaction__rea_gene__gene__morbid__disorder__icontains=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='dita':
                    objs = Compound.objects.filter(rea_comp__reaction__rea_gene__gene__dis_target__disease__icontains=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='drug':
                    objs = Compound.objects.filter(rea_comp__reaction__rea_gene__gene__drug_target__drug__icontains=f.cleaned_data["seterm"]).distinct()
                else:
                  objs=Compound.objects.all()
                if f.cleaned_data["pa"]:
                  if not f.cleaned_data["pa"][0][0]=='0':
                    objs=objs.filter(rea_comp__reaction__pathway__in=f.cleaned_data["pa"]).distinct()     
                if f.cleaned_data["lo"]:
                  if not f.cleaned_data["lo"][0][0]=='0':
                    objs=objs.filter(rea_comp__reaction__realoc__loc__in=f.cleaned_data["lo"]).distinct()     
                if f.cleaned_data["t"]:
                  if not f.cleaned_data["t"][0][0]=='0':
                    objs=objs.filter(rea_comp__reaction__reatissue__tissue__in=f.cleaned_data["t"]).distinct()     
                return render_to_response('compound_list.html', {'compound_list': objs})
             if f.cleaned_data["sefor"]=='gene':
                if f.cleaned_data["seterm"]:
                  if f.cleaned_data["se"]=='rea':
                    objs = Gene.objects.filter(rea_gene__reaction__reactionid__icontains=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='com':
                    qset = (
                      Q(rea_gene__reaction__rea_comp__compound__name__icontains=f.cleaned_data["seterm"]) |
                      Q(rea_gene__reaction__rea_comp__compound__compoundid__icontains=f.cleaned_data["seterm"]) 
                    )
                    objs = Gene.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='entrez':
                    qset = (
                      Q(name=f.cleaned_data["seterm"]) |
                      Q(geneid=f.cleaned_data["seterm"]) 
                    )
                    objs = Gene.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='hgen':
                    qset = (
                      Q(hgnc=f.cleaned_data["seterm"]) |
                      Q(ensembl=f.cleaned_data["seterm"]) 
                    )
                    objs = Gene.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='uniprot':
                    qset = (
                      Q(uniprot__icontains=f.cleaned_data["seterm"]) |
                      Q(altprotein__icontains=f.cleaned_data["seterm"]) 
                    )
                    objs = Gene.objects.filter(qset).distinct()
                  if f.cleaned_data["se"]=='ec':
                    objs = Gene.objects.filter(rea_gene__reaction__rea_ec__enzyme=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='dig':
                    objs = Gene.objects.filter(morbid__disorder__icontains=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='dita':
                    objs = Gene.objects.filter(dis_target__disease__icontains=f.cleaned_data["seterm"]).distinct()
                  if f.cleaned_data["se"]=='drug':
                    objs = Gene.objects.filter(drug_target__drug__icontains=f.cleaned_data["seterm"]).distinct()
                else:
                  objs=Gene.objects.all()
                if f.cleaned_data["pa"]:
                  if not f.cleaned_data["pa"][0][0]=='0':
                    objs=objs.filter(rea_gene__reaction__pathway__in=f.cleaned_data["pa"]).distinct()     
                if f.cleaned_data["lo"]:
                  if not f.cleaned_data["lo"][0][0]=='0':
                    objs=objs.filter(geneloc__loc__in=f.cleaned_data["lo"]).distinct()     
                return render_to_response('gene_list.html', {'gene_list': objs})
    else:
        f = searchform()
        return render_to_response('search2.html', {'form': f})

class netviewform(forms.Form):
    foptions=[('svg','svg'),('png','png'),('gif','gif'),('jpg','jpg')]
#    foptions=[('jpg','jpg'),('png','png'),('gif','gif'),('bmp','bmp'),('svg','svg'),
#              ('dot','dot'),('eps','eps'),('ps','ps'),('pdf','pdf')]
    poptions=[('dot','dot'),('neato','neato'),('twopi','twopi'),('fdp','fdp')]
    fformat=forms.ChoiceField(label="format", choices=foptions,required=False)
    prog=forms.ChoiceField(label="program", choices=poptions,required=False)
    rlabel=forms.BooleanField(label="reaction label",required=False)
    mlabel=forms.BooleanField(label="metabolite label",required=False)
    size=forms.CharField(label="node size", help_text='0.02 to 0.5. or type 1 to fit node label', required=False)

def mgraphvisnew(request): #try to generate network picture without lables,
    #only works for small network now. Why take very long time to generate a layout
    #without lable but very fast for a graph with lable.
    colors=[]
    for i in range(1,100):
      s3=str((i % 6)/5.0)
      s2=i/6
      if s2>5:
        s1=str(s2/6/2.0)
        s2=str((s2 %6)/5.0)
      else:
        if i==5:
          s3="0.000" #replace white with black
        s1="0.000"
        s2=str(s2/5.0)
      colors.append(s1+" "+s2+" "+s3)
    reas=request.session['ehmnr']
    metlinks=Met_link.objects.filter(rea__in=reas)
#    Gd = pydot.Dot(graph_type='digraph')
    G = pydot.Dot()
    G.set_concentrate("true")
    if request.method == 'GET':
        f = netviewform(request.GET)
        if not f.is_valid():
           return render_to_response('kdotviewnew.html', {'form': f}) #do sth else 
        else:
           f.cleaned_data["rlabel"]="T" #to be commented to show graph without lables
           f.cleaned_data["mlabel"]="T"
           if f.cleaned_data["fformat"]:
              fformat=f.cleaned_data["fformat"]
           else:   
              fformat='svg'
           if f.cleaned_data["prog"]:
              prog=f.cleaned_data["prog"]
           else:   
              prog='dot'
           for link in metlinks:
              e=pydot.Edge(link.com1.name,link.com2.name, URL="/reaction/"+link.rea.reactionid, tooltip=link.rea.equation,target='_blank')
              if f.cleaned_data["rlabel"]:
                 e.set_label(link.rea.reactionid)
#                 e.set_labeltooltip(link.rea.eq_in_id)
                 e.set_labeltooltip(link.rea.pathway.name)
              e.set_arrowsize("0.2")
              e.set_color(colors[link.rea.pathway.pathid])
              e.set_fontcolor(colors[link.rea.pathway.pathid])
              G.add_edge(e)
              if f.cleaned_data["mlabel"]:
                n1=pydot.Node(link.com1.name, URL="/compound/"+link.com1.compoundid,target='_blank')
                n2=pydot.Node(link.com2.name, URL="/compound/"+link.com2.compoundid,target='_blank')
              else:  
                if f.cleaned_data["size"]:
                  size=f.cleaned_data["size"]
                else:   
                  size="0.05"
                n1=pydot.Node(link.com1.name, fixedsize="1", height=size,width=size,URL="/kegg/cpd/"+link.com1.compoundid,target='_blank')
                n2=pydot.Node(link.com2.name, fixedsize="1", height=size,width=size,URL="/kegg/cpd/"+link.com2.compoundid,target='_blank')
                n1.set_label("") #try this first
                n2.set_label("") #try this first
                n1.set_tooltip(link.com1.name) #try this first
                n2.set_tooltip(link.com2.name) #try this first
              G.add_node(n1)
              G.add_node(n2)
           G.write(MEDIA_ROOT+'mg'+prog+'.'+fformat, prog=prog,format=fformat)
#           if fformat=='svg':
#              image=open('c:/human/media/mg'+prog+'.svg',"rb").read()
#              return HttpResponse(image, mimetype="image/svg+xml")
#           else: 
           return render_to_response("kdotviewnew.html", {'form': f,'prog':prog,'format': fformat})

def showpath(request, pname):
   reaction_list=Reaction.objects.filter(pathway__name__icontains=pname)
   return render_to_response("reaction_list.html", locals())

def showpathloc(request, pname,loname):
  import pydot
  metlink_list=Met_link.objects.filter(pathway__name=pname,rea__rea_gene__gene__geneloc__loc__abs=loname).distinct()
  G = pydot.Dot()
  for link in metlink_list:
              e=pydot.Edge(link.com1.name,link.com2.name,label=link.rea.reactionid,URL='/reaction/'+link.rea.reactionid)
              e.set_URL('/reaction/'+link.rea.reactionid)
              G.add_edge(e)
              n=pydot.Node(link.com1.name,URL="/compound/"+link.com1.compoundid)
              G.add_node(n)
              n=pydot.Node(link.com2.name,URL="/compound/"+link.com2.compoundid)
              G.add_node(n)
  G.write(MEDIA_ROOT+pname+loname+'.svg', prog='dot',format='svg')
  image=open(MEDIA_ROOT+pname+loname+".svg","rb").read()
  return HttpResponse(image, mimetype="image/svg+xml")

def showpathloc2(request, pname,loname):
  import pydot
  metlink_list=Met_link.objects.filter(pathway__name=pname,rea__realoc__loc__abs=loname).distinct()
  G = pydot.Dot()
  for link in metlink_list:
              e=pydot.Edge(link.com1.name,link.com2.name,label=link.rea.reactionid,URL='/reaction/'+link.rea.reactionid)
              e.set_URL('/reaction/'+link.rea.reactionid)
              G.add_edge(e)
              n=pydot.Node(link.com1.name,URL="/compound/"+link.com1.compoundid)
              G.add_node(n)
              n=pydot.Node(link.com2.name,URL="/compound/"+link.com2.compoundid)
              G.add_node(n)
  G.write(MEDIA_ROOT+pname+loname+'.svg', prog='dot',format='svg')
  image=open(MEDIA_ROOT+pname+loname+".svg","rb").read()
  return HttpResponse(image, mimetype="image/svg+xml")

class pathviewform(forms.Form):
    foptions=[('jpg','jpg'),('png','png'),('gif','gif'),('svg','svg')]
#    foptions=[('jpg','jpg'),('png','png'),('gif','gif'),('bmp','bmp'),('svg','svg'),
#              ('dot','dot'),('eps','eps'),('ps','ps'),('pdf','pdf')]
    poptions=[('dot','dot'),('neato','neato'),('twopi','twopi'),('fdp','fdp')]
    fformat=forms.ChoiceField(label="format", choices=foptions,required=False)
    prog=forms.ChoiceField(label="program", choices=poptions,required=False)
    rlabel=forms.BooleanField(label="reaction label",required=False)
    mlabel=forms.BooleanField(label="metabolite label",required=False)

def showpathgraph(request, pname):
#   import networkx as nx
   import pydot
   metlink_list=Met_link.objects.filter(pathway__name=pname)
#   el=[]
   s=''
   G = pydot.Dot()
   if request.method == 'GET':
        f = pathviewform(request.GET)
        if not f.is_valid():
           return render_to_response('dotview.html', {'form': f,'pname':'wrong'}) #do sth else 
        else:
           if f.cleaned_data["fformat"]:
              fformat=f.cleaned_data["fformat"]
           else:   
              fformat='jpg'
           if f.cleaned_data["prog"]:
              prog=f.cleaned_data["prog"]
           else:   
              prog='dot'
           for link in metlink_list:
#     el.append((link.com1.compoundid,link.com2.compoundid, link.rea.reactionid))
#     el.append((link.com1.name,link.com2.name, link.rea.reactionid))
#   G=pydot.graph_from_edges(el)
#method 2 with reaction label
              e=pydot.Edge(link.com1.name,link.com2.name)
              if f.cleaned_data["rlabel"]:
                 e.set_label(link.rea.reactionid)
              e.set_URL('/reaction/'+link.rea.reactionid)
#     e.set_URL('/admin/ehmn/reaction/'+link.rea.reactionid)
              if link.rea.reactionid[1]=='E':
#     if link.rea in search1.objs:
                 e.set_color('red')
                 e.set_style("setlinewidth(3)")
              G.add_edge(e)
           if not f.cleaned_data["mlabel"]:
#              nlist=G.get_node_list()
#              for node in nlist:
#                 node.set_label("") #not change at all
#              G.write('media/'+pname+'.dot', prog=None, format='dot')
#              dotf=open('media/'+pname+'.dot', 'r')
#              s=dotf.read()
#              dotf.close()
              s=G.to_string()
              p=s.find('{')
#              s=s[0:p+16]+s[p+18:]
              dotf=open('c:/human/media/'+pname+'.dot', 'w')
              dotf.write(s[0:p+1])
              dotf.write('node [label=\"\\N\"];')
              nlist=G.get_node_list()
              for node in nlist:
#                 node.set_label("") #not change at all
                 dotf.write(node.get_name())
              dotf.write(s[p+2:])
              dotf.close()
              G=pydot.graph_from_dot_file(MEDIA_ROOT+pname+'.dot')
#              s=s.replace("\N","")
#              G=pydot.graph_from_dot_data(G.to_string()) #this function does not work,read file is ok
           G.write(MEDIA_ROOT+pname+'.'+fformat, prog=prog,format=fformat)
           if fformat=='svg':
              image=open(MEDIA_ROOT+pname+".svg","rb").read()
              return HttpResponse(image, mimetype="image/svg+xml")
           else: 
              return render_to_response("dotview.html", {'form': f,'s':s,'format': fformat,'pname':pname})
#     G.write('media/'+pname+'.dot', prog=None, format='raw')
#   G=pydot.graph_from_dot_file('1.dot')
#   return HttpResponse(image, mimetype="image/svg+xml")
#   return HttpResponse(image, mimetype="image/jpg")
#   G.write_imap(pname+'.map', prog='dot')
#write to dot before layout, then add node [label=""] in dot file to hide label;



def metgraph(request):
    reas=request.session['r']
    metlinks=Met_link.objects.filter(rea__in=reas)
    G=nx.MultiDiGraph()
#    Gd = pydot.Dot(graph_type='digraph')
#    mls=[]
    for ml in metlinks:
        rev=ml.rea.reversibility
#        mls.append((ml.com1,ml.com2,ml.rea,rev))
#        mls.append((ml.com1.name,ml.com2.name,ml.rea,rev))
        #Creating a new list with extra columns including information from other tables
        #is one way to transfer multiple table information to the template
        #another way is to creat a function in the model class which returns a value
        #based on data from related table
        #for this case, the best way may be to include the reversibility column in the table
#        G.add_edge(ml.com1,ml.com2)
        G.add_edge(ml.com1.compoundid,ml.com2.compoundid,lable=ml.rea.reactionid)
#        G.add_edge(ml.com1.name,ml.com2.name,lable=ml.rea.reactionid)
#        e=pydot.Edge(ml.com1.name,ml.com2.name,label=ml.rea.reactionid,URL='http://www.kegg.jp/dbget-bin/www_bget?rn:'+ml.rea.reactionid)
#        e=pydot.Edge(ml.com1.name,ml.com2.name)
#        e.set_label(ml.rea.reactionid)
#        e.set_URL('http://www.kegg.jp/dbget-bin/www_bget?rn:'+ml.rea.reactionid)
#        Gd.add_edge(e)
        if not rev:
#          G.add_edge(ml.com1,ml.com2)
          G.add_edge(ml.com2.compoundid,ml.com1.compoundid,lable=ml.rea.reactionid)
#          G.add_edge(ml.com2.name,ml.com1.name,lable=ml.rea.reactionid)
#          e=pydot.Edge(ml.com2.name,ml.com1.name)
#          e.set_label(ml.rea.reactionid)
#          e.set_URL('http://www.kegg.jp/dbget-bin/www_bget?rn:'+ml.rea.reactionid)
#          Gd.add_edge(e)
    nmet=G.number_of_nodes()
    nlink=G.size()
    al=nx.average_shortest_path_length(G)
    UG=G.to_undirected()
 #   cluster=nx.average_clustering(UG) #not for mutiple graph
    con=nx.is_connected(UG)
    request.session['mgraph']=G
#    request.session['mgraphdot']=Gd
    return render_to_response('kmetlink.html', locals())

def shortpath(request): #avoid repeat reaction using breadth first search, paths as list of edges with rea data
#    from django.core.exceptions import ObjectDoesNotExist
#    fps2=open("c:/human/media/ps2.txt","w") for debuging
    if request.method == 'GET':
      f = pathform(request.GET)
      if not f.is_valid():
           err="sth wrong"
           return render_to_response('kpath.html', locals()) #do sth else 
      else:
        c1id=f.cleaned_data["com1"]
        c2id=f.cleaned_data["com2"]
        G=request.session['mgraph']
        flag=0
        paths=[]
        if c1id in G and c2id in G:
            ns=[c1id]+G.neighbors(c1id)
            if c2id in ns:
              rs=G.get_edge_data(c1id,c2id).values()
              for r in rs:
                path=[[c1id,c2id,r['lable']]]
                paths.append(path)
            else:    
              ps=G.out_edges(c1id,data=True) #just use ps
              ps2=[] #for the searched paths
              for p in ps:
                ps2.append([[p[0],p[1],p[2]['lable']]])  #change from a list of turple to a list of list
              while flag==0: #stop after find a path to c2, may be two or more paths
                newnodes=[] #for new nodes from all the existing nodes, while "newns" for new nodes from a specific node
                newps=[] #new paths to be found
                for p in ps2:
#                  newns=G.neighbors(p[-1][1])
#                  newnodes=newnodes+newns
                  newedges=G.out_edges(p[-1][1],data=True)
                  if newedges: #possible no out links
                    for ne in newedges:
                      r=ne[2].values()[0]
                      if not r==p[-1][2]:
                        if ne[1]==c2id:
                          path=p+[[ne[0],ne[1],r]] #list of list
                          paths.append(path)
                          flag=1
                        elif not ne[1] in ns: #neighbours may include nodes already found (loop)
                          newp=p+[[ne[0],ne[1],r]] #list of list
                          newps.append(newp)
                          if not ne[1] in newnodes:
                            newnodes.append(ne[1])
#                  if c2id in newns: #need to check, as maybe target in newns but not change flag as repeat rea. just do a through search
#                      rs=G.get_edge_data(p[-1][1],c2id).values()
#                      for r in rs:
#                        if not r['lable']==p[-1][2]:
#                          flag=1
#                          path=p+[[p[-1][1],c2id,r['lable']]] #list of list
#                          paths.append(path)
#                  else:
                ps2=newps
#                fps2.write(str(ps2)+"\n")
                ns=ns+newnodes #change ns after searching for all nodes to find multiple shortest paths 
            Gd=pydot.Dot()
#            fps2.close()
            edges=[] #to avoid repeat edges
            nodes=[]
            for p in paths: #should keep rea info in paths, then will not need to search metlink again.
              for e in p:
                if not e in edges:
                  edges.append(e)
                  rea=Reaction.objects.get(reactionid=e[2])
                  edot=pydot.Edge(e[0],e[1],label=e[2],tooltip=rea.eq_in_id,labeltooltip=rea.equation)
                  edot.set_URL("/kegg/rn/"+e[2])
                  Gd.add_edge(edot)
                  if not e[0] in nodes:
                    nodes.append(e[0]) 
                    node=pydot.Node(e[0],URL="/kegg/cpd/"+e[0])
                    cname=Compound.objects.get(compoundid=e[0]).name
                    node.set_label(cname)
#                    node.set_tooltip(cname)
                    Gd.add_node(node)
#            nodes.append(c2id) 
            node=pydot.Node(c2id,URL="/kegg/cpd/"+c2id)
            cname=Compound.objects.get(compoundid=c2id).name
            node.set_label(cname)
#            node.set_tooltip(cname)
            Gd.add_node(node)
            Gd.write(MEDIA_ROOT+'path.png', prog="dot",format="png")
            Gd.write(MEDIA_ROOT+'path.svg', prog="dot",format="svg")
            image=open(MEDIA_ROOT+'path.svg',"rb").read()
            return HttpResponse(image, mimetype="image/svg+xml")
        else:
            err="the compounds are not in the network"
            return render_to_response('kpath.html', locals())